//
//  LoginSellerViewController.m
//  SmartCoin
//
//  Created by apple on 2018/3/7.
//  Copyright © 2018年 Cynic. All rights reserved.
//

#import "LoginSellerViewController.h"
#import "SellerMainViewController.h"
#import <JPUSHService.h>
#import "LoginRuleViewController.h"
@interface LoginSellerViewController ()
@property (nonatomic ,retain)UIView *centerView;
@property (nonatomic ,retain)UITextField *accountfield;
@property (nonatomic ,retain)UITextField *secretfield;
@end

@implementation LoginSellerViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
     self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    cxsingler;
    self.view.backgroundColor = [UIColor whiteColor];
    [self viewLoad];
}

-(void)viewLoad{
    [self bgload];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyHidden:) name:UIKeyboardWillHideNotification object:nil];
    [self centerViewLoad];
}


//顶部背景图片
-(void)bgload{
    UIImageView *topbg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cx_wid,770.0 / 750 * cx_wid +  cxsingler.navitop + cxsingler.topdis -  cxsingler.navitop)];
    topbg.image = [UIImage imageNamed:@"背景图2"];
    
    UIImageView *logo = [[UIImageView alloc] init];
    logo.image = [UIImage imageNamed:@"logo1"];
    logo.bounds = CGRectMake(0, 0, 103, 103);
    logo.center = CGPointMake(cx_wid / 2, 91 + 51.5);
    [topbg addSubview:logo];
    
    [self.view addSubview:topbg];
}

-(void)centerViewLoad{
    CGFloat hit =  327.0 / 299 * (cx_wid - 38 * 2);
    _centerView = [[UIView alloc] initWithFrame:CGRectMake(38, cx_hit - hit - [self getrealHit:90], cx_wid - 38 * 2, hit)];
    _centerView.layer.cornerRadius = 5;
    _centerView.layer.shadowOffset = CGSizeMake(3, 3);
    _centerView.layer.shadowOpacity = 0.5;
    _centerView.layer.shadowColor = [UIColor grayColor].CGColor;
    _centerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_centerView];

#pragma mark--输入信息
    NSArray *typenames = @[@"phone",@"pass"];
    NSArray *placeholders = @[@"输入帐号或手机号",@"请输入密码"];
    for (NSInteger index = 0; index < 2; index ++) {
        UIView *partView = [[UIView alloc] initWithFrame:CGRectMake(27,[self getrealHit:(62.5 + 60 * index)], _centerView.bounds.size.width - 54, [self getrealHit:40])];
//        partView.backgroundColor = [UIColor orangeColor];
        UIView *layerview = [[UIView alloc] init];
        layerview.backgroundColor = [CXSinglerModel colorWithHex:@"e0e0e0" alpha:1];
        [partView addSubview:layerview];
        [layerview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(0);
            make.left.mas_equalTo(0);
            make.right.mas_equalTo(0);
            make.height.mas_equalTo(0.5);
        }];
        [_centerView addSubview:partView];
        
        UIImageView *typeview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 10, 20, 20)];
        typeview.image = [UIImage imageNamed:typenames[index]];
        UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(30, 10, partView.bounds.size.width - 30 - 10 - 30, 20)];
        if (index == 0) {
            _accountfield = field;
            field.max = 11;
            field.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"count"];
            field.keyboardType = UIKeyboardTypeNumberPad;
        }
        else if(index == 1){
            field.max = 12;
            _secretfield = field;
            if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"lock"] integerValue] == 0) {
                field.text = @"";
                [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"pass"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
            else{
            field.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"pass"];
            }
//            __weak typeof(field) weakField = field;
//            [field cx_eventsChangeByHandler:^{
//                NSLog(@"newlen = %ld",weakField.text.length);
//            }];
            field.secureTextEntry = YES;
            UIButton *lockBtn = [[UIButton alloc] initWithFrame:CGRectMake(partView.bounds.size.width - 30 - 10, 5, 30, 30)];
//            lockBtn.backgroundColor = [UIColor purpleColor];
            [lockBtn setImage:[UIImage imageNamed:@"unlock"] forState:UIControlStateNormal];
            [lockBtn setImage:[UIImage imageNamed:@"lock"] forState:UIControlStateSelected];
            if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"lock"] integerValue] == 1) {
                lockBtn.selected = YES;
            }
            __weak typeof(lockBtn) weakLock = lockBtn;
            [lockBtn cx_eventsBlockHandler:^{
                weakLock.selected = !weakLock.selected;
                if (weakLock.selected) {
                    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"lock"];
                }
                else{
                    [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"lock"];
                }
                [[NSUserDefaults standardUserDefaults] synchronize];
            } forControlEvents:UIControlEventTouchUpInside];
            if (![[NSUserDefaults standardUserDefaults] objectForKey:@"lock"]) {
                [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"lock"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
            if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"lock"] integerValue] == 0) {
                lockBtn.selected = NO;
            }
            else{
                lockBtn.selected = YES;
            }
            [partView addSubview:lockBtn];
        }
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldEditChanged:)
                                                    name:@"UITextFieldTextDidChangeNotification"
                                                  object:field];

        [partView addSubview:typeview];
        [partView addSubview:field];
        field.placeholder = placeholders[index];
        field.font = [UIFont systemFontOfSize:16];
    }
#pragma mark--登录按钮
    UIButton *enterBtn = [[UIButton alloc] init];
    [_centerView addSubview:enterBtn];
    [enterBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(_centerView.mas_centerX);
        make.bottom.mas_equalTo(_centerView.mas_bottom).with.offset(-[self getrealHit:65]);
        make.size.mas_equalTo(CGSizeMake(_centerView.bounds.size.width - 46 , 40));
    }];
    enterBtn.clipsToBounds = YES;
    [enterBtn addTarget:self action:@selector(enter:) forControlEvents:UIControlEventTouchUpInside];
    CAGradientLayer *layer = [CAGradientLayer layer];
    layer.frame = CGRectMake(0, 0, cx_wid - 46 - 38 * 2, 40);
    layer.colors = @[(id)[CXSinglerModel colorWithHex:@"#FF7F5A" alpha:1].CGColor,(id)[CXSinglerModel colorWithHex:@"#FE4438" alpha:1].CGColor];
    layer.startPoint = CGPointMake(0, 0);
    layer.endPoint = CGPointMake(1, 0);
    [enterBtn.layer addSublayer:layer];
    [enterBtn setTitle:@"登录" forState:UIControlStateNormal];
    [enterBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    enterBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    enterBtn.layer.cornerRadius = 20;
    
#pragma mark--noticepart
    UIButton *noticelabel = [[UIButton alloc] initWithFrame:CGRectMake(0, cx_hit - cxsingler.bottomdis - 30 , cx_wid, 16)];
//    noticelabel.text = ;
    NSMutableAttributedString *rulename = [[NSMutableAttributedString alloc] initWithString:@"登录即代表同意《用户使用协议》"];
    [rulename addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, rulename.length)];
    [rulename addAttribute:NSForegroundColorAttributeName value:[CXSinglerModel colorWithHex:@"2734fb" alpha:1] range:NSMakeRange(7, 8)];
    [noticelabel setAttributedTitle:rulename forState:UIControlStateNormal];
    [noticelabel addTarget:self action:@selector(ruled:) forControlEvents:UIControlEventTouchUpInside];
//    noticelabel.titleLabel.textAlignment = NSTextAlignmentCenter;
    noticelabel.titleLabel.font = [UIFont systemFontOfSize:15];
//    noticelabel.textColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.4];
    [noticelabel setTitleColor:[[UIColor lightGrayColor] colorWithAlphaComponent:0.4] forState:UIControlStateNormal];
    [self.view addSubview:noticelabel];
    
    UIButton *pop = [[UIButton alloc] initWithFrame:CGRectMake(0, cxsingler.topdis, 44, 44)];
    [pop setImage:[UIImage imageNamed:@"return"] forState:UIControlStateNormal];
    [pop addTarget:self action:@selector(pop:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:pop];
}

-(void)pop:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark--键盘监听
-(void)keyShow:(NSNotification *)notice{
    CGRect rect = [notice.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    double duration = [notice.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        _centerView.center = CGPointMake(cx_wid / 2, cx_hit - cxsingler.bottomdis - rect.size.height + 30 - _centerView.bounds.size.height / 2);
    }];
    //    }
}

-(void)keyHidden:(NSNotification *)notice{
    double duration = [notice.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        CGFloat hit =  327.0 / 299 * (cx_wid - 38 * 2);
        _centerView.frame = CGRectMake(38, cx_hit - hit - [self getrealHit:90], cx_wid - 38 * 2, hit);
    }];
}

#pragma mark--点击
#pragma mark--空白恢复
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing: YES];
}

#pragma mark--登录
-(void)enter:(UIButton *)sender{
    [self.view endEditing:YES];
    if (![Utils isTelephone:_accountfield.text]) {
        [SVProgressHUD showErrorWithStatus:@"请使用有效手机帐号"];
        return;
    }
    if (![Utils isPassword:_secretfield.text]) {
        [SVProgressHUD showErrorWithStatus:@"请使用有效密码"];
        return;
    }
    NetWorkModel *netModel = [[NetWorkModel alloc] init];
    [SVProgressHUD showWithStatus:@"登录中..."];
    NSString *count = _accountfield.text;
    NSString *pass = _secretfield.text;
    [netModel loginwithUserAccount:_accountfield.text withPass:_secretfield.text];
    WEAKSELF;
    netModel.sendMessage = ^(NSString *result) {
        if ([result isEqual:@"success"]) {
//            [SVProgressHUD showSuccessWithStatus:@"登录成功"];
            dispatch_async(dispatch_get_main_queue(), ^{
            [[NSUserDefaults standardUserDefaults]  setObject:count forKey:@"count"];
            });
            if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"lock"] integerValue] == 1) {//密码锁
                dispatch_async(dispatch_get_main_queue(), ^{
                [[NSUserDefaults standardUserDefaults] setObject:pass forKey:@"pass"];//沙盒存储密码
                    [[NSUserDefaults standardUserDefaults] synchronize];//更新沙盒
                NSLog(@"remember");
                });
            }
            else{
                dispatch_async(dispatch_get_main_queue(), ^{
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"pass"];//沙盒移除密码
                [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"pass"];
                    [[NSUserDefaults standardUserDefaults] synchronize];//更新沙盒
                NSLog(@"forget");
                    });
            }
            NSString *aliascode = [NSString stringWithFormat:@"ID_%ld",[cxsingler.loginrequest[@"admin"][@"id"] integerValue]];//设置推送别名
            NSLog(@"alisecode = %@",aliascode);
//            aliascode = @"cxtestcoder";
            [JPUSHService setAlias:aliascode completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {//注册别名，用语推送

                if (iResCode != 0) {
                    NSLog(@"---Alex---:\n极光别名注册失败");
                }
            } seq:111111];
            [weakSelf containNumLoad];
            
        }
        else{
            [SVProgressHUD showErrorWithStatus:result];
        }
    };
}

-(void)containNumLoad{
    NetWorkModel *netmodel = [[NetWorkModel alloc] init];
    [netmodel getSegNum];
    WEAKSELF;
    netmodel.sendMessage = ^(NSString *result) {
        if([result isEqual:@"success"]){
        [SVProgressHUD showSuccessWithStatus:@"登录成功"];
        cxsingler.sellersegnum = 2 + [cxsingler.StrData integerValue];
        SellerMainViewController *sellerVC = [[SellerMainViewController alloc] init];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.navigationController pushViewController:sellerVC animated:YES];
                weakSelf.navigationController.interactivePopGestureRecognizer.enabled = NO;
            });
       
        }
        else{
            [SVProgressHUD showErrorWithStatus:result];
        }
    };
}


#pragma mark--录入规则
-(void)textFieldEditChanged:(NSNotification *)obj{//帐号11位以内，密码10位以内
    NSInteger max = 11;
    UITextField *textField = (UITextField *)obj.object;
    
    if ([textField isEqual:_secretfield]) {
        max = 10;
    }
    NSString *toBeString = textField.text;

    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position)
    {
        if (toBeString.length > max)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:max];
            if (rangeIndex.length == 1)
            {
                textField.text = [toBeString substringToIndex:max];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, max)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
        //        _noticeLabel.text = [NSString stringWithFormat:@"%ld/%ld",textField.text.length,max];
    }
}


-(void)ruled:(UIButton *)sender{
    LoginRuleViewController *nextVC = [[LoginRuleViewController alloc] init];
    [self.navigationController pushViewController:nextVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
